<?php

namespace app\index\controller;

use think\Request;
use think\Controller;
use think\Db;
use Exception;


class synstudydata extends Controller{

    public $cid = 0;
    public $db = 0;
    public $startTime = ''; //开始时间
    public $endTime = '';   //结束时间

    public function __construct(){
        die;
        $this->startTime = microtime(true);
        $request = Request::instance();
        $env = $request->param('env');//test product 测试、正式
        $line = $request->param('line');//classba 171xue 线上、线下
        $subject = $request->param('subject'); //math en cn  科目,现在只有数学、英语、语文

        if(
                !in_array($env, ['test','product']) || 
                !in_array($line, ['classba','171xue']) || 
                !in_array($subject, ['math','en','cn'])
        ){
            exit('参数错误');
        }

        echo "<pre>";
        $this->cid  = $this->getCid($subject);
        $this->db  = $this->getBussinessDb($env,$line,$subject);//获取业务库
        $this->bussinessTable = $this->getBussinessTable($subject);//获取业务表
        $this->api_url = $this->getApiUrl($env,$line);
        if(!$this->api_url){
            exit('Api接口未给出');
        }
    }



    //读入接口数据
    public function cache(){
        $cid = $this->cid;
        $db = $this->db;
        $bussinessTable = $this->bussinessTable;
        $api_url = $this->api_url;
        
        $page = 1;
        $pagesize = 200;
        $startTime = microtime(true);
        while(true){
            $offset = ($page-1) * $pagesize;
            $data  = Db::connect($db)->table('ct_user_study_exam_temp')
                    ->field(["id,user_id,topic_id,course_id"])
                    ->limit($offset,$pagesize)
                    ->order('id','asc')
                    ->select();
            if($data){
                $dataList = [];
                foreach ($data as $v) {
                    $param = [
                        'user_id'=>$v['user_id'],
                        'topic_id'=>$v['topic_id'],
                        'course_id'=>$v['course_id'],
                        'cid'=>$cid
                    ];
                    try{
                        $getData = $this->getInterfaceInfo($api_url, $param, $db, $v['id']);
                    }catch (Exception $e) {
                        print $e->getMessage();
                        exit();
                    }
                    
                    $item = [
                        'temp_id'=>$v['id'],
                        'user_id'=> $getData['user_id'],
                        'topic_id'=>$getData['topic_id'],
                        'study_card_id'=> $getData['study_card_id'],
                        'study_card_name'=> $getData['study_card_name'],
                        'section_id'=> $getData['section_id'],
                        'section_name'=> $getData['section_name'],
                        'course_id'=> $getData['course_id'],
                        'course_name'=> $getData['course_name'],
                        'cid'=> $getData['cid'],
                        'result'=> json_encode($getData['result']),
                        'ctime' =>time()
                    ];
                    $dataList[] = $item;
                }
                $res = Db::connect($db)->table('ct_user_study_exam_temp_cache')->insertAll($dataList);
                sleep(1);

                if($res){
                    $page++;
                }
            }else{

                break;
            }
        }

    }


    //本地读入
    public function run(){
        $request = Request::instance();
        $env = $request->param('env');//test product 测试、正式
        $line = $request->param('line');//classba 171xue 线上、线下
        $subject = $request->param('subject'); //math en cn  科目,现在只有数学、英语、语文

        if(!in_array($env, ['test','product']) || !in_array($line, ['classba','171xue']) || !in_array($subject, ['math','en','cn'])){
            exit('参数错误');
        }

        $cid  = $this->getCid($subject);
        $db  = $this->getBussinessDb($env,$line,$subject);//获取业务库
        $bussinessTable = $this->getBussinessTable($subject);//获取业务表
        $api_url = $this->getApiUrl($env,$line);
        if(!$api_url){
            exit('Api接口未给出');
        }

        echo "<pre>";
        $page = 1;
        $pagesize = 200;
        $startTime = microtime(true);


        while(true){
            $offset = ($page-1) * $pagesize;

            $data  = Db::connect($db)->table($bussinessTable)
                    ->field(["id,user_id,course_id,topic_id as topicId"])
                    // ->field(["qid as id,user_id,course_id,topic_id as topicId"])
                    ->limit($offset,$pagesize)
                    ->order('id','asc')
                    ->select();
            // echo Db::connect($db)->getLastSql();die;
            if($data){
                $dataList = [];//正确数据
                $dataList1 = [];//错误数据

                foreach ($data as $v) {
                    $where = [
                        'user_id'=>$v['user_id'],
                        'course_id'=>$v['course_id'],
                        'topic_id'=>$v['topicId'],
                        // 'section_id'=>$v['section_id'],
                        'cid'=>$cid
                    ];
                    //读缓存表
                    $getData = Db::connect($db)->table('ct_user_study_exam_temp_cache')->where($where)->find();

                    if(!$getData){
                        echo "缓存表不存在数据:".json_encode($where).",detail_id:".$v['id'];
                        die;
                    }

                    $item = [
                        'detail_id'=>$v['id'],
                        'user_id'=> $getData['user_id'],
                        'topic_id'=>$getData['topic_id'],
                        'study_card_id'=> $getData['study_card_id'],
                        'study_card_name'=> $getData['study_card_name'],
                        'section_id'=> $getData['section_id'],
                        'section_name'=> $getData['section_name'],
                        'course_id'=> $getData['course_id'],
                        'course_name'=> $getData['course_name'],
                        'cid'=> $getData['cid'],
                        'ctime' =>time()
                    ];
                    if($getData['study_card_id'] == 0){
                        $dataList1[] = $item;
                    }else{
                        $dataList[] = $item;
                    }
                }

                if($dataList){
                    $res = Db::connect($db)->table('ct_user_study_exam_info')->insertAll($dataList);
                }
                if($dataList1){
                    $res1 = Db::connect($db)->table('ct_user_study_exam_info_error')->insertAll($dataList1);
                }
                if($res || $res1){
                    $page++;
                }
            }else{
                break;
            }
        }

        $endTime = microtime(true);
        $runtime = sprintf("%.5f",($endTime-$startTime));
        echo "------------------------------总耗时:$runtime";

    }



    public function getInterfaceInfo($api_url,$param,$db,$temp_id){
        $return_data = rpc_request($api_url, $param);
        if($return_data['code']==1)
        {
            $user_id = $param['user_id'];
            $course_id = $param['course_id'];
            $topic_id = $param['topic_id'];
            $cid = $param['cid'];

            $data1 = '';
            if(isset($return_data['data']) && isset($return_data['data'][0])){
                $data1 = $return_data['data'][0];
            }

            $course_name = $data1?$data1['course_name']:'';
            $section_id = $data1?$data1['section_id']:0;
            $section_name = $data1?$data1['section_name']:'';
            $study_card_id = 0;
            if($data1 && $data1['study_card_list'] && $data1['study_card_list'][0]['study_card_id']){
                $study_card_id = $data1['study_card_list'][0]['study_card_id'];
            }
            $study_card_name = '';
            if($data1 && $data1['study_card_list'] && $data1['study_card_list'][0]['study_card_name']){
                $study_card_name = $data1['study_card_list'][0]['study_card_name'];
            }

            $data2 = [
                'temp_id'=>$temp_id,
                'user_id'=>$user_id,
                'course_id'=>$course_id,
                'course_name'=>$course_name,
                'topic_id'=>$topic_id,
                'section_id'=>$section_id,
                'section_name'=>$section_name,
                'cid'=>$cid,
                'study_card_id'=>$study_card_id,
                'study_card_name'=>$study_card_name,
                'result'=>$data1,
                'ctime'=>time()
            ];
            return $data2;
        }else{
            var_dump($api_url, $param, $temp_id,$return_data);
            throw new Exception("Api接口返回错误，错误信息：".$return_data['msg']);
        } 

    }

    public function getBussinessDb($env,$line,$subject)
    {
        $config = [
            'test'=>[//测试
                'classba'=>[
                    'math' => [//用来测试
                        'type'           => 'mysql',// 数据库类型
                        'hostname'       => '106.14.172.5',// 服务器地址
                        'database'       => 'jupiter_math_v2_0523',// 数据库名
                        // 'database'       => 'jupiter_math_v2',// 数据库名
                        'username'       => 'root',// 用户名
                        'password'       => 'projectx2015',// 密码
                        'hostport'       => '',// 端口
                    ],                    
                    'en' => [
                        'type'           => 'mysql',// 数据库类型
                        'hostname'       => '106.14.172.5',// 服务器地址
                        'database'       => 'jupiter_en_v2_0706',// 数据库名
                        // 'database'       => 'jupiter_en_v2_0523',// 数据库名
                        // 'database'       => 'jupiter_en_reading_0601',// 数据库名
                        'username'       => 'root',// 用户名
                        'password'       => 'projectx2015',// 密码
                        'hostport'       => '',// 端口
                    ],
                    'cn' => [
                        'type'           => 'mysql',// 数据库类型
                        'hostname'       => '106.14.172.5',// 服务器地址
                        'database'       => 'jupiter_cn_v2_0523',// 数据库名
                        'username'       => 'root',// 用户名
                        'password'       => 'projectx2015',// 密码
                        'hostport'       => '',// 端口
                    ],
                ],                
                '171xue'=>[
                    'math' => [
                        'type'           => 'mysql',// 数据库类型
                        'hostname'       => '106.14.172.5',// 服务器地址
                        'database'       => 'online_jupiter_math_v2_0531',// 数据库名
                        // 'database'       => 'online_jupiter_math_v2_0426',// 数据库名----------
                        'username'       => 'root',// 用户名
                        'password'       => 'projectx2015',// 密码
                        'hostport'       => '',// 端口
                    ],
                    'en' => [
                        'type'           => 'mysql',// 数据库类型
                        'hostname'       => '106.14.172.5',// 服务器地址
                        'database'       => 'online_jupiter_en_v2',// 数据库名
                        'username'       => 'root',// 用户名
                        'password'       => 'projectx2015',// 密码
                        'hostport'       => '',// 端口
                    ],
                    'cn' => [
                        'type'           => 'mysql',// 数据库类型
                        'hostname'       => '106.14.172.5',// 服务器地址
                        'database'       => 'online_jupiter_cn_v2',// 数据库名
                        'username'       => 'root',// 用户名
                        'password'       => 'projectx2015',// 密码
                        'hostport'       => '',// 端口
                    ],
                ],
            ],
            'product'=>[//生产
                'classba'=>[//线下
                    'math' => [
                        'type'           => 'mysql',// 数据库类型
                        'hostname'       => 'yixue-classba-01.mysql.rds.aliyuncs.com',// 服务器地址
                        'database'       => 'jupiter_math_v2',// 数据库名
                        'username'       => 'db_admin',// 用户名
                        'password'       => 'Projectx@2017',// 密码
                        'hostport'       => '',// 端口
                    ],
                    'en' => [
                        'type'           => 'mysql',// 数据库类型
                        'hostname'       => 'yixue-classba-01.mysql.rds.aliyuncs.com',// 服务器地址
                        'database'       => 'jupiter_en_v2',// 数据库名
                        'username'       => 'db_admin',// 用户名
                        'password'       => 'Projectx@2017',// 密码
                        'hostport'       => '',// 端口
                    ],
                    'cn' => [
                        'type'           => 'mysql',// 数据库类型
                        'hostname'       => 'yixue-classba-01.mysql.rds.aliyuncs.com',// 服务器地址
                        'database'       => 'jupiter_cn_v2',// 数据库名
                        'username'       => 'db_admin',// 用户名
                        'password'       => 'Projectx@2017',// 密码
                        'hostport'       => '',// 端口
                    ],
                ],                
                '171xue'=>[//线上
                    'math' => [
                        'type'           => 'mysql',// 数据库类型
                        'hostname'       => 'yixue-online-01.mysql.rds.aliyuncs.com',// 服务器地址
                        'database'       => 'online_jupiter_math_v2',// 数据库名
                        'username'       => 'db_admin',// 用户名
                        'password'       => 'Projectx@2017',// 密码
                        'hostport'       => '',// 端口
                    ],
                    'en' => [
                        'type'           => 'mysql',// 数据库类型
                        'hostname'       => 'yixue-online-01.mysql.rds.aliyuncs.com',// 服务器地址
                        'database'       => 'online_jupiter_en_v2',// 数据库名
                        'username'       => 'db_admin',// 用户名
                        'password'       => 'Projectx@2017',// 密码
                        'hostport'       => '',// 端口
                    ],
                    'cn' => [
                        'type'           => 'mysql',// 数据库类型
                        'hostname'       => 'yixue-online-01.mysql.rds.aliyuncs.com',// 服务器地址
                        'database'       => 'online_jupiter_cn_v2',// 数据库名
                        'username'       => 'db_admin',// 用户名
                        'password'       => 'Projectx@2017',// 密码
                        'hostport'       => '',// 端口
                    ],
                ],
            ],

        ];
        return $config[$env][$line][$subject];//读取数据库配置
    }


    public function getBussinessTable($subject){
        $table_config = [
            'math'=>'ct_user_exam_detail',
            'en'=>'ct_user_questions',
            // 'en'=>'ct_questions_log',
            'cn'=>'ct_user_exam_detail',
        ];
        return $table_config[$subject];
    }

    public function getApiUrl($env,$line){
        //api地址配置
        $api_config = [
                    'test'=>[//测试
                        'classba'=>'http://dev-api.51yxedu.com/api.php/Course/getCourseRelateInfo',
                        // 'classba'=>'http://test-api.51yxedu.com/api.php/Course/getCourseRelateInfo',
                        '171xue' =>'http://test-api3.171xue.com/api.php/course/getCourseRelateInfo'
                    ],
                    'product'=>[//正式
                        'classba'=>'',
                        '171xue'=>''
                    ],
        ];
        return $api_config[$env][$line];
    }

    public function getCid($subject){
        $subject_config = ['en'=>1, 'math'=>2, 'cn'=>3, 'phy'=>4];
        return $subject_config[$subject];//科目编号
    }


    public function __destruct(){
        $this->endTime = microtime(true);
        $runtime = sprintf("%.5f",($this->endTime-$this->startTime));
        echo "------------------------------总耗时:$runtime";
    }



}